package com.happy.unitconvert.common.exception;

import com.happy.unitconvert.common.result.Result;
import com.happy.unitconvert.common.result.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

  private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

  /**
   * 处理业务异常
   */
  @ExceptionHandler(BusinessException.class)
  public ResponseEntity<Result<Void>> handleBusinessException(BusinessException e, HttpServletRequest request) {
    logger.warn("业务异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());
    return ResponseEntity.ok(Result.error(e.getResultCode()));
  }

  /**
   * 处理参数校验异常 - RequestBody
   */
  @ExceptionHandler(MethodArgumentNotValidException.class)
  public ResponseEntity<Result<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e,
      HttpServletRequest request) {
    logger.warn("参数校验失败: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());

    String errorMsg = e.getBindingResult().getFieldErrors().stream()
        .map(FieldError::getDefaultMessage)
        .collect(Collectors.joining("; "));

    return ResponseEntity.badRequest().body(Result.error(ResultCode.PARAM_INVALID.getCode(), errorMsg, null));
  }

  /**
   * 处理参数校验异常 - RequestParam
   */
  @ExceptionHandler(ConstraintViolationException.class)
  public ResponseEntity<Result<String>> handleConstraintViolationException(ConstraintViolationException e,
      HttpServletRequest request) {
    logger.warn("参数校验失败: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());

    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    String errorMsg = violations.stream()
        .map(ConstraintViolation::getMessage)
        .collect(Collectors.joining("; "));

    return ResponseEntity.badRequest().body(Result.error(ResultCode.PARAM_INVALID.getCode(), errorMsg, null));
  }

  /**
   * 处理参数绑定异常
   */
  @ExceptionHandler(BindException.class)
  public ResponseEntity<Result<String>> handleBindException(BindException e, HttpServletRequest request) {
    logger.warn("参数绑定失败: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());

    String errorMsg = e.getFieldErrors().stream()
        .map(FieldError::getDefaultMessage)
        .collect(Collectors.joining("; "));

    return ResponseEntity.badRequest().body(Result.error(ResultCode.PARAM_INVALID.getCode(), errorMsg, null));
  }

  /**
   * 处理缺少请求参数异常
   */
  @ExceptionHandler(MissingServletRequestParameterException.class)
  public ResponseEntity<Result<Void>> handleMissingServletRequestParameterException(
      MissingServletRequestParameterException e, HttpServletRequest request) {
    logger.warn("缺少请求参数: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());
    String message = String.format("缺少必需的请求参数: %s", e.getParameterName());
    return ResponseEntity.badRequest().body(Result.error(ResultCode.BAD_REQUEST.getCode(), message, null));
  }

  /**
   * 处理参数类型不匹配异常
   */
  @ExceptionHandler(MethodArgumentTypeMismatchException.class)
  public ResponseEntity<Result<Void>> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e,
      HttpServletRequest request) {
    logger.warn("参数类型不匹配: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());
    String message = String.format("参数 %s 类型不正确", e.getName());
    return ResponseEntity.badRequest().body(Result.error(ResultCode.BAD_REQUEST.getCode(), message, null));
  }

  /**
   * 处理请求方法不支持异常
   */
  @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  public ResponseEntity<Result<Void>> handleHttpRequestMethodNotSupportedException(
      HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
    logger.warn("请求方法不支持: {}, 请求路径: {}", e.getMessage(), request.getRequestURI());
    return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED)
        .body(Result.error(ResultCode.METHOD_NOT_ALLOWED));
  }

  /**
   * 处理404异常
   */
  @ExceptionHandler(NoHandlerFoundException.class)
  public ResponseEntity<Result<Void>> handleNoHandlerFoundException(NoHandlerFoundException e,
      HttpServletRequest request) {
    logger.warn("请求路径不存在: {}", request.getRequestURI());
    return ResponseEntity.status(HttpStatus.NOT_FOUND)
        .body(Result.error(ResultCode.NOT_FOUND));
  }

  /**
   * 处理其他未知异常
   */
  @ExceptionHandler(Exception.class)
  public ResponseEntity<Result<Void>> handleException(Exception e, HttpServletRequest request) {
    logger.error("系统异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI(), e);
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
        .body(Result.error(ResultCode.INTERNAL_SERVER_ERROR));
  }
}
